package com.airsystem.pos.bengkel.controller.dialog;

import java.util.Vector;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import com.airsystem.pos.bengkel.component.TableFrame;
import com.airsystem.pos.bengkel.entity.JenisTagihan;
import com.airsystem.pos.bengkel.interfaces.ILookup;
import com.airsystem.pos.bengkel.interfaces.IServices;
import com.airsystem.pos.bengkel.interfaces.ISystem;
import com.airsystem.pos.bengkel.model.dialog.MasterBillingDialogModel;
import com.airsystem.pos.bengkel.service.JenisTagihanServices;
import com.airsystem.pos.bengkel.util.Preconditions;

/**
 * @author Fanny Irawan Sutawanir (fannyirawans@gmail.com)
 */
public class MasterBillingDialogController extends MasterBillingDialogModel implements ILookup, ISystem {
	private static final Logger LOG = Logger.getLogger(MasterBillingDialogController.class.getSimpleName());

	private IServices<JenisTagihan> service;

	public MasterBillingDialogController() {
		super();

		service = new JenisTagihanServices();
	}

	public void setup() {
		TableFrame.deleteTable(tableData, tableModel);
	}

	public void get() {
		JenisTagihan jenisTagihan = new JenisTagihan();
		jenisTagihan.setId(Long.parseLong(tableData.getValueAt(row, 1).toString()));
		jenisTagihan.setNama(tableData.getValueAt(row, 0).toString());

		setJenisTagihan(jenisTagihan);
	}

	public void reset() {
		searchField.setText("");
		searchCombo.requestFocus();
	}

	public void category() {
		throw new UnsupportedOperationException("Not Implemented.");
	}

	public void search() {
		try {
			Preconditions.checkEmpty(searchField);
		} catch (IllegalArgumentException e) {
			JOptionPane.showMessageDialog(this, "Silahkan input data!", "Pesan", JOptionPane.WARNING_MESSAGE);
			reset();

			return;
		}

		try {
			setup();
			Iterable<JenisTagihan> tagihans = service.select(getSearchData());

			for (JenisTagihan item : tagihans) {
				Vector<String> vector = new Vector<String>();
				vector.add(item.getNama());
				vector.add(item.getId_s());

				tableModel.addRow(vector);
			}

			tableData.setModel(tableModel);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			JOptionPane.showMessageDialog(this, "Load data gagal!", "Pesan", JOptionPane.ERROR_MESSAGE);
		}
	}

	public void load() {
		try {
			setup();
			Iterable<JenisTagihan> tagihans = service.select(new JenisTagihan());

			for (JenisTagihan item : tagihans) {
				Vector<String> vector = new Vector<String>();
				vector.add(item.getNama());
				vector.add(item.getId_s());

				tableModel.addRow(vector);
			}
			tableData.setModel(tableModel);

			this.setVisible(true);
		} catch (Exception e) {
			this.setVisible(false);
			LOG.error(e.getMessage(), e);
			JOptionPane.showMessageDialog(this, "Load data gagal!", "Pesan", JOptionPane.ERROR_MESSAGE);
		}
	}
}